//
//  CourseViewController.m
//  xpkc
//
//  Created by wanmeizty on 14-8-18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "CourseViewController.h"
#import "UserMessage.h"
#import "OffLineViewController.h"
#import "MJRefresh.h"
@interface CourseViewController ()

@end

@implementation CourseViewController{
    NSMutableArray *listDataArray;
    NSMutableArray *sectionCloseArray;
    int sectionIndex;
    int videoCount;
//    NSMutableArray *videoArray;
    OffLineViewController *OLVC;
    CourseViewLogin *loginView;
    UILabel * label;
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.navigationItem.title = @"我的课程";
        self.tabBarItem.title = @"课程";
        self.tabBarItem.image =[UIImage imageNamed:@"tab_course"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_course_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    self.navigationItem.leftBarButtonItem = nil;
    sectionCloseArray = [[NSMutableArray alloc]init];
    //创建视图
    [self creatListView];
    OLVC = [[OffLineViewController alloc]init];
}

- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [listDataArray removeAllObjects];
    [sectionCloseArray removeAllObjects];
    label.hidden=YES;
    
    if ([GetNetworkStatues getReachability]) {
    }else{
        ShowAlertMsg(@"请检查网络连接");
    }
    
    if ( ![UserMessage sharedUserMessage].isLogin ) {
        logdebug(@"未登录");
        loginView.hidden = NO;
    }else{
        loginView.hidden = YES;
        
        [self getCourseListInfo];
           
        
    }
}


- (void)creatNavItem{
    UIImage *downimg = [UIImage imageNamed:@"shopcart"];
    if (IsIOS7) {
        downimg = [downimg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    UIBarButtonItem *downManager = [[UIBarButtonItem alloc]initWithImage:downimg style:UIBarButtonItemStyleBordered target:self action:@selector(downManagerVC)];
    downManager = [[UIBarButtonItem alloc]initWithTitle:@"离线管理" style:UIBarButtonItemStyleBordered target:self action:@selector(downManagerVC)];
    [downManager setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = downManager;
}

/**
 *  创建视图
 */
-(void)creatListView{
    self.view.backgroundColor = [UIColor whiteColor];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getCourseListInfo)];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    //设置位置与样式
    self.tableView = [[UITableView alloc]initWithFrame:RECT(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-50) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.header = header;
    [self.view addSubview:self.tableView];
    
    //登录页
    loginView = [[CourseViewLogin alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 40)];
    loginView.hidden = YES;
    loginView.delegate = self;
    [self.view addSubview:loginView];
}
- (void)downManagerVC{
    
    [self.navigationController pushViewController:OLVC animated:YES];
}
/**
 *  下载课程列表
 */
-(void)getCourseListInfo{
    listDataArray = [[NSMutableArray alloc]init];


    NSString *module = @"myCourse";
    NSString *interface = @"courselist";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid};
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //成功
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        

        if (dic.count == 0) {
            label  = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/3, SCREEN_HEIGHT/2-50-64, SCREEN_WIDTH/3, 50)];
            label.textAlignment=NSTextAlignmentCenter;
            label.textColor=[UIColor darkGrayColor];
            label.text=@"暂无下载课程";
            [self.view addSubview:label];
             [self.tableView.header endRefreshing];
            
          
        }else{
            label.hidden=YES;
        NSArray *courseListArray = [dic objectForKey:@"courseList"];
        //返回状态,成功,失败,查询失败
        int success = [[dic objectForKey:@"succ"]intValue];
        int error = [[dic objectForKey:@"error"]intValue];
        int selerror = [[dic objectForKey:@"selerror"]intValue];
        if (success) {
            logdebug(@"获取课程列表成功");
            logdebug(@"共%d课程",(int)courseListArray.count);
        }
        if (error) {
            logdebug(@"获取课程列表失败");
        }
        if (selerror) {
            logdebug(@"课程列表查找失败");
        }
        [listDataArray removeAllObjects];
        [sectionCloseArray removeAllObjects];
        for (NSDictionary *courseDic in courseListArray) {
            //获取数据
            NSArray *classDicArray = [courseDic objectForKey:@"classMsg"];
            NSString *courseName = [courseDic objectForKey:@"packAgeName"];
            NSMutableArray *classArray = [[NSMutableArray alloc]init];
            for (NSDictionary *classDic in classDicArray) {
                
                NSLog(@"classDic==>%@",classDic);
                
                NSString *classid = [classDic objectForKey:@"classId"];
                NSString *className = [classDic objectForKey:@"className"];
                ClassModel *classModel = [[ClassModel alloc]init];
                classModel.teacher = classDic[@"teacher"];
                
                
                
                classModel.leo = [NSString stringWithFormat:@"%@",classDic[@"leo"]]; //[classDic[@"leo"] stringValue];
                classModel.myprogress = [NSString stringWithFormat:@"%@",classDic[@"myprogress"]];//[classDic[@"myprogress"] stringValue];
                classModel.class_full_name = classDic[@"class_full_name "];
                classModel.classID = classid;
                classModel.className = className;
                classModel.courseNum = [NSString stringWithFormat:@"%@",classDic[@"courseNum"]];// [classDic[@"courseNum"] stringValue];
                classModel.endtime = classDic[@"endtime"];
                [classArray addObject:classModel];
            }
            CourseModel *courseModel = [[CourseModel alloc]init];
            courseModel.courseName = courseName;
            courseModel.classArray = classArray;
            courseModel.teacher = [courseDic objectForKey:@"teacher"];
            courseModel.endtime = [courseDic objectForKey:@"endtime"];
            courseModel.packAgeName = courseName;
            [listDataArray addObject:courseModel];
        }
        //设置标记数组
        for (int i = 0; i<listDataArray.count; i++) {
            NSNumber *num = [NSNumber numberWithInt:0];
            [sectionCloseArray addObject:num];
        }
        if ([[NSUserDefaults standardUserDefaults]valueForKey:LASTLESSON] == NULL) {
            
        }else{
            int num = [[[NSUserDefaults standardUserDefaults]valueForKey:LASTLESSON]intValue];
            if (num < sectionCloseArray.count) {
                [sectionCloseArray replaceObjectAtIndex:num withObject:[NSNumber numberWithInt:1]];
            }
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        }
        [hud hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //失败
        logdebug(@"%@",error.localizedDescription);
        [self.tableView.header endRefreshing];
    
        [hud hide:YES];
    }];
}
#pragma mark - tableview delegate
//课程数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return listDataArray.count;
}
//课程标题高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	return SCREEN_WIDTH >320?SCREEN_HEIGHT * (140/1334.0):70;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 35;
}
//每个课程的班次
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    CourseModel *model = [listDataArray objectAtIndex:section];
    //根据数组的标记来判断0收起
    if (([[sectionCloseArray objectAtIndex:section]intValue] == 0)) {
        return 0;
    }else{
        return model.classArray.count;
    }
}
//自定义headerView 使用的是按钮（或者其他都行）
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (listDataArray.count == 0) {
        return [[UIView alloc] init];
    }
    CourseModel *model = [listDataArray objectAtIndex:section];
    CourseViewCellHeaderView *header =[[CourseViewCellHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 70)];
    header.courseIcon.image = [UIImage imageNamed:@"abc"];
//    header.courseTitle.text = model.courseName;
//    header.validTerm.text = @"2015-04-31";
//    header.teacher.text = @"王老吉";
    header.courseTitle.text = model.packAgeName;
    NSLog(@"%@",model.packAgeName);
    
    header.courseTitle.font = [UIFont boldSystemFontOfSize:16];
    NSString * endtime = [[model.endtime componentsSeparatedByString:@" "] firstObject];
    header.validTerm.text = endtime;
    header.teacher.text = model.teacher;
    
    header.layer.borderColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1].CGColor;
    header.layer.borderWidth = 0.3;
    header.tag = section;
    [header addTarget:self action:@selector(sectionClick:) forControlEvents:UIControlEventTouchUpInside];
    if ([[sectionCloseArray objectAtIndex:section]intValue] == 0) {
        [header.openFlag setTransform:CGAffineTransformMakeRotation(-M_PI_2)];
    }else{
        [header.openFlag setTransform:CGAffineTransformMakeRotation(0)];
    }
    return header;
}

-(void)sectionClick:(UIButton *)btn{
//    logdebug(@"%d",[[sectionCloseArray objectAtIndex:btn.tag]intValue]);
    if ([[sectionCloseArray objectAtIndex:btn.tag]intValue] == 0) {
        //重置
//        logdebug(@"%@",sectionCloseArray);
        int num = [[[NSUserDefaults standardUserDefaults]valueForKey:LASTLESSON]intValue];
        [sectionCloseArray replaceObjectAtIndex:num withObject:[NSNumber numberWithInt:0]];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:num] withRowAnimation:UITableViewRowAnimationFade];
        [sectionCloseArray replaceObjectAtIndex:btn.tag withObject:[NSNumber numberWithInt:1]];
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%ld",(long)btn.tag] forKey:LASTLESSON];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        [sectionCloseArray replaceObjectAtIndex:btn.tag withObject:[NSNumber numberWithInt:0]];
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%ld",(long)btn.tag] forKey:LASTLESSON];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationFade];
}
//班次classcell
-(CourseViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CourseViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[CourseViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    if (listDataArray.count == 0) {
        return cell;
    }
    CourseModel *courseModel = [listDataArray objectAtIndex:indexPath.section];
    ClassModel *classModel = [courseModel.classArray objectAtIndex:indexPath.row];
	
    if ([classModel.className isKindOfClass:[NSNull class]]) {
    } else {
        cell.className = classModel.className;
        cell.teacherName = classModel.teacher;//@"王霞";
        cell.studied = [classModel.myprogress intValue] ;;
        cell.study = [classModel.courseNum intValue];
    }

    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
//选择了某个课程
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //获取到详细信息
    CourseModel *courseModel = [listDataArray objectAtIndex:indexPath.section];
    ClassModel *classModel = [courseModel.classArray objectAtIndex:indexPath.row];
    
    CourseVideoViewController *CVVC = [[CourseVideoViewController alloc]init];
    CVVC.hidesBottomBarWhenPushed = YES;
    CVVC.classId = classModel.classID;
    [self.navigationController pushViewController:CVVC animated:YES];
    return;
////
    
    
    /*************************************/
    //跳转界面
    CourseVideoListViewController *courseVideoVC = [[CourseVideoListViewController alloc]init];
    logdebug(@"%@",courseVideoVC.classId);
    courseVideoVC.classId = classModel.classID;
    courseVideoVC.mid = [UserMessage sharedUserMessage].userMid;
    courseVideoVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:courseVideoVC animated:YES];
    if (IsIOS7) {
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        }
    }
    
}


#pragma mark - course login delegate
- (void)loginWithUsername:(NSString *)username andPassword:(NSString *)password{
    
    NSString *module = @"userLogin";
    NSString *interface = @"loginfo";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"userName":username,@"userPWD":[password md5]};
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"登录中";
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //密码记得MD5加密一下
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //完成
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        /**
         *  判断发送请求的格式是否正确，不正确的话返回的参数是比较蛋疼的
         */
        if ([dic objectForKey:@"timerror"]) {
            logdebug(@"faterror:退出登录");
            [UserMessage sharedUserMessage].isLogin = NO;
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确保手机时间与北京时间相差五分钟以内" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            return ;
        }
        int success = [[dic objectForKey:@"succ"]intValue];
        if (success) {
            //登录成功
            //记录登录成功的用户的设备类型和当前版本
            //            //设备类型
            //            NSString *strModel  = [UIDevice currentDevice].model;
            //            logdebug(@"%@",strModel);
            //            //当前系统版本
            //            NSString *syslVersion = [[UIDevice currentDevice] systemVersion];
            //            logdebug(@"%@",sysVersion);
            //成功
            [loginView loginStatue:LoginStatueSucc];
            NSDictionary *data = [dic objectForKey:@"data"];
            NSString *mid = [data objectForKey:@"mid"];
            NSString *userid = [data objectForKey:@"userid"];
            NSString *headimg = [data objectForKey:@"face"];
            logdebug(@"%@",data);
            logdebug(@"\nNo.%@\nUserName:%@\n  [登录成功]",mid,userid);
            //保存登录信息
            [UserMessage sharedUserMessage].isLogin = YES;
            [UserMessage sharedUserMessage].userId = [data objectForKey:@"userid"];//用户名
            [UserMessage sharedUserMessage].userMid = [data objectForKey:@"mid"];//数字
            [[NSUserDefaults standardUserDefaults] setValue:[UserMessage sharedUserMessage].userMid forKey:USERMID_REMBER];
            [[NSUserDefaults standardUserDefaults] setValue:[UserMessage sharedUserMessage].userId forKey:USERNAME_REMBER];
            [[NSUserDefaults standardUserDefaults] setValue:headimg forKey:USERHEAD_REMBER];
              [[NSUserDefaults standardUserDefaults]setValue:password forKey:PASSWORD_REMBER];
            [[NSUserDefaults standardUserDefaults] synchronize];//记录usermid
            [self viewWillAppear:YES];
        }
        int errorPWD = [[dic objectForKey:@"errorPwd"]intValue];
        if (errorPWD) {
            //密码错误
            [loginView loginStatue:LoginStatuePasswordError];
        }
        int errorAcc = [[dic objectForKey:@"errorAcc"]intValue];
        if (errorAcc) {
            //用户名错误
            [loginView loginStatue:LoginStatueUsernameError];
        }
        [hud hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ShowAlertMsg(@"请求超时，请检查网络并重新登录");
        [loginView loginStatue:LoginStatueInternetError];
        [hud hide:YES];
    }];
}
- (void)regist{
    RegistViewController *RVC = [[RegistViewController alloc]init];
    RVC.title = @"用户注册";
    RVC.hidesBottomBarWhenPushed = YES;
    RVC.delegate = self;
    [self.navigationController pushViewController:RVC animated:YES];
}
- (void)forgot{
    RetrieveViewController *RVC = [[RetrieveViewController alloc]init];
    RVC.title = @"密码找回";
    RVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:RVC animated:YES];
}

- (void)fillUserName:(NSString *)username andPassWord:(NSString *)password{
    [loginView fillUsername:username andPassword:password];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
